import java.io.File
import java.io.FileInputStream
import java.util.Properties
import kotlin.system.exitProcess

const val KEY_API_ID = "API_ID"
const val KEY_API_TOKEN = "API_TOKEN"
const val KEY_DOMAIN = "DOMAIN"
const val KEY_SUB_DOMAIN = "SUB_DOMAIN"
const val KEY_STORE_DB = "STORE_DB"
const val KEY_LOG_LEVEL = "LOG_LEVEL"
const val KEY_WEBHOOK = "WEBHOOK"

fun main(args: Array<String>) {
    val config = Properties()
    val configFile = if (args.size > 1) args[args.size - 1] else "config.properties"
    if (!File(configFile).isFile) {
        Logger.e("config file not exists, use ddns {file} to specify one")
        exitProcess(1)
    }
    FileInputStream(configFile).run {
        config.load(this)
        close()
    }

    val apiId = config.getProperty(KEY_API_ID)
    val apiToken = config.getProperty(KEY_API_TOKEN)
    val domain = config.getProperty(KEY_DOMAIN)
    val subDomain = config.getProperty(KEY_SUB_DOMAIN)
    val logLevel = config.getProperty(KEY_LOG_LEVEL)
    val storeDb = config.getProperty(KEY_STORE_DB).toBoolean()
    val webhook = config.getProperty(KEY_WEBHOOK)

    if (!logLevel.isNullOrEmpty()) {
        Logger.logLevel = logLevel.toInt()
    }

    if (apiId == null || apiToken == null || domain == null || subDomain == null) {
        Logger.e("missing required parameters")
        exitProcess(1)
    }

    if (webhook != null && !webhook.startsWith("http")) {
        Logger.e("webhook only support http(s) protocol")
        exitProcess(1)
    }

    val helper = DNSHelper(domain, subDomain, apiId, apiToken)
    val urlIp = helper.getUrlIp()
    if (urlIp == null) {
        Logger.e("get url ip fail")
        exitProcess(1)
    }
    Logger.d("urlIp: $urlIp")
    val dnsIp = helper.getDnsIp()
    if (dnsIp == null) {
        Logger.w("get dns ip fail")
    }
    Logger.d("dnsIp: $dnsIp")
    if (dnsIp == urlIp) return

    val dnspodIp = helper.getDnspodIp()
    if (dnspodIp == null) {
        Logger.e("get dnspod ip fail")
        exitProcess(1)
    }
    Logger.d("dnspodIp: $dnspodIp")
    if (dnspodIp.value == urlIp) return

    Logger.i("ip changed\nurlIp: $urlIp\ndnsIp: $dnsIp\ndnspodIp: ${dnspodIp.value}")

    val updateResult = helper.updateDnspodIp(dnspodIp, urlIp)
    if (!updateResult) exitProcess(1)

    Logger.i("update success")

    val listeners = ArrayList<IpChangedListener>()
    if (storeDb) {
        listeners.add(DBIpChangedListener())
    }
    if (!webhook.isNullOrEmpty()) {
        listeners.add(WebhookIpChangedListener(webhook))
    }

    for (listener in listeners) {
        listener.onIpChanged(urlIp, dnsIp, dnspodIp.value)
    }
}